﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Dynamic;
using Data.Repositories;
using CantinhodaCegonha.Models.Helpers;
using System.IO;

namespace CantinhodaCegonha.Controllers
{
    public class ToolsController : Controller
    {
        //
        // GET: /Tools/

        public ActionResult Index(string param)
        {
            return View();
        }

        public ActionResult SignificadoNome(string nome ="",string gender="all")
        {
            NomesRepository nrep = new NomesRepository();
            var res = nrep.getNomes(nome, gender);

            if (nome.Contains("Pesquisar") || nome=="")
            {
                if (gender == "all")
                    ViewBag.mensagem = "Não indicou nenhum nome para pesquisa. Irão ser listados todos os nomes.";
                else
                {
                    string sexo = gender == "F" ? "feminino" : "masculino";
                    ViewBag.mensagem = "Não indicou nenhum nome para pesquisa. Irão ser listados todos os nomes do sexo <b>" + sexo + "</b>.";
                }
                return View(res);
            }

            var encontrado = res.ToList().Find(x => Util.RemoveDiacritics(x.NomeProprio.ToUpper()) == Util.RemoveDiacritics(nome.ToUpper()));
            string genero = "";
            if (encontrado != null)
            {
                genero = encontrado.Genero == "F" ? "Feminino" : "Masculino";
                string style = encontrado.Genero == "F" ? "style=\"color:#E85B85\"" : "style=\"color:#41748C\"";
                string output = "<li><h1 " + style + ">" + encontrado.NomeProprio;
                output +="<span style=\"margin-left:10px\">" + Microsoft.Web.Helpers.Facebook.LikeButton("http://www.cantinhodacegonha.com/Tools/SignificadoNome", "button_count", false, 450, 20, "like") + "</span></h1></li>";
                output += "<li><b style=\"font-size: 15px;\">Significado:</b> " + encontrado.Descricao + "</li>";
                ViewBag.DescricaoNome = output;
                ViewBag.gender = encontrado.Genero;
                ViewBag.Descricao = encontrado.Descricao;
                ViewBag.Nome = encontrado.NomeProprio;
                return View(res.Where(x=>x.Genero == encontrado.Genero));
            }
            else
            {
                ViewBag.mensagem = "O nome <b>" + Request.QueryString["nome"] + "</b> não foi encontrado. Mostramos mais nomes que começam com a mesma letra.";
            }

            
            return View(res);
        }

        [HttpPost]
        public JsonResult NomeDetails(int id)
        {
            NomesRepository nrep = new NomesRepository();
            var tmp = nrep.GetNome(id);
            NomeDetailsJson detail = new NomeDetailsJson();
            detail.NomeProprio = tmp.NomeProprio;
            detail.Descricao = tmp.Descricao;
            detail.FacebookUrl = Microsoft.Web.Helpers.Facebook.LikeButton("http://www.cantinhodacegonha.com/Tools/SignificadoNome?nome="+detail.NomeProprio, "button_count", false, 130, 20, "like").ToHtmlString();
            detail.Genero = tmp.Genero;
            return Json(detail);
        }


        public ActionResult OvulationCalc(int? cycleLength, DateTime? ov_date)
        {
            int valor=0;
            if (!ov_date.HasValue || cycleLength == null)
            {
                return View();
            }
            valor = cycleLength.Value;

            //data estimada de ovulação
            DateTime dt7 = ov_date.Value.AddDays(14);

            int diasParto = 280-11;

            dynamic Modelo = new ExpandoObject();
            
            //Data inicial fertil
            Modelo.DataFertilInicial = ov_date.Value.AddDays(11);
            //data final fertil
            Modelo.DataFertilFinal = ov_date.Value.AddDays(16);

            //data de nascimento previsto
            Modelo.DataNascimento = ov_date.Value.AddDays(diasParto);

            SignoRepository signos = new SignoRepository();
            ViewBag.signo = signos.GetSigno(Modelo.DataNascimento);
            ViewBag.SignoChines = signos.GetSignoChines(Modelo.DataNascimento);

            List<string[]> lst = new List<string[]>();
            for (int i = 0; i < 5; i++)
            {
                DateTime dt = Modelo.DataFertilInicial.AddDays(valor);
                lst.Add(new string[] { dt.ToString("d MMMM, yyyy"), 
                    Modelo.DataFertilFinal.AddDays(valor).ToString("d MMMM, yyyy"), 
                    dt.AddDays(diasParto).ToString("d MMMM, yyyy") });
                valor += 28;
            }
            Modelo.Datas = lst;

            return View(Modelo);
        }

        public ActionResult Signo(string nome)
        {
            SignoRepository signo = new SignoRepository();
            List<SelectListItem> lst = new List<SelectListItem>();
            foreach (var item in signo.GetAllSignos())
            {
                lst.Add(new SelectListItem { Text = item.Nome + "(" + item.DiaInicial.ToString("dd-MM") + " a " + item.DiaFinal.ToString("dd-MM") + ")", Value = item.Id.ToString() });
            }
            ViewBag.Lst = lst;

            return View(signo.GetSignoByNome(nome));
        }

        public ActionResult CompatibilidadeSigno(int? SignoOrg,int? SignoDest)
        {
            
            SignoRepository signo = new SignoRepository();
            List<SelectListItem> lst = new List<SelectListItem>();
            foreach (var item in signo.GetAllSignos())
            {
                lst.Add(new SelectListItem { Text = item.Nome + "(" + item.DiaInicial.ToString("dd-MM") + " a " + item.DiaFinal.ToString("dd-MM") + ")", Value = item.Id.ToString() });
            }
            ViewBag.Lst = lst;
            if (SignoOrg == null || SignoDest == null) return View();
            return View(signo.GetCompatibilidades(SignoOrg.Value,SignoDest.Value));
        }

        public ActionResult SignoChines(string nome)
        {
            if (nome == null) return View();
            SignoRepository signo = new SignoRepository();
            return View(signo.GetSignoChinesByNome(nome));
        }

        [HttpPost]
        public ActionResult SignoChinesData(DateTime? datachines)
        {
            if (!datachines.HasValue) { return RedirectToAction("SignoChines"); }
            else
            {
                SignoRepository signo = new SignoRepository();
                return RedirectToAction("SignoChines", new { nome = signo.GetSignoChines(datachines.Value).Animal });
            }
        }


        public ActionResult DetalheData(DateTime? datadetalhe)
        {
            if (!datadetalhe.HasValue)
            {
                ViewBag.MostraData = true;
            }else
            {
                ViewBag.MostraData = false;
                ViewBag.Data = datadetalhe.Value.ToString("dd MMMM");
                DatasRepository datarep = new DatasRepository();
                ViewBag.Pessoas = datarep.GetPessoasFamosas(datadetalhe.Value);
                SignoRepository signo = new SignoRepository();
                ViewBag.Signo = signo.GetSigno(datadetalhe.Value);
                ViewBag.SignoChines = signo.GetSignoChines(datadetalhe.Value);
            }
            return View();
        }

        [HttpPost]
        public ActionResult SignNewsletter(string tentar, DateTime? family_date, string email)
        {
            if (email != "email@endereço.com" && email != "" || (tentar == "1" && family_date.HasValue))
            {
                NewsletterRepository rep = new NewsletterRepository();
                rep.Aderir(tentar, family_date, email);
            }
            return Redirect("/");
        }

        [OutputCache(VaryByParam = "none", Duration = 300)]
        public ActionResult RSS()
        {
            ArtigoRepository artrep = new ArtigoRepository();
            var artigos = artrep.GetAllArtigosRSS();
            if (artigos == null)
                return View("NotFound");

            return new RssResult(artigos.ToList(), "Cantinho da cegonha - Artigos recentes");
        }


        public ActionResult IndiceMassaCorporal(int? altura,int? peso)
        {
            if (!altura.HasValue || !peso.HasValue)
            {
                return View();
            }
            else
            {

                if ((altura.Value < 100 && altura.Value > 250) || (peso.Value < 25 && peso.Value > 250))
                    return View(); //Erro

                double alt = altura.Value / 100.0;
                double alt1 = alt * alt;
                double bmi = Math.Round(peso.Value / alt1, 1);
                double minBMI = 18.5;
                double maxBMI = 24.9;
                string ms004 = "O seu peso está dentro nos parâmetros normais.",
                        ms018 = "O seu peso está ",
                        ms019 = " kilogramas ",
                        ms020 = " abaixo do normal.",
                        ms026 = "Você tem ",
                        ms027 = " kilogramas ",
                        ms028 = " de peso a mais.",
                        retorno ="";

                if ((bmi >= minBMI) && (bmi <= maxBMI))
                {
                    retorno = ms004;  // "Your weight is in the normal range.";
                }
                else
                {
                    if (bmi < minBMI)
                    {
                        double i = Math.Round(alt1 * minBMI - peso.Value,1);
                        //double i1 = Math.Round(i * 2.2,1); //     ms018 = "You are underweight by "; ms019 = " kilograms (";  ms020 = " pounds).<br/>\n";
                        retorno = ms018 + i + ms019 + ms020;
                    }
                    if (bmi > maxBMI)
                    {
                        double i = Math.Round(peso.Value - alt1 * maxBMI,1);
                        //double i1 = Math.Round(i * 2.2,1); //     ms026 = "You are overweight by ";  ms027 = " kilograms (";  ms028 = " pounds)";
                        retorno = ms026 + i + ms027 + ms028;
                    }
                }
                ViewBag.massacorporal = bmi;
                ViewBag.massa = retorno;
                return View();                
            }
        }

        public ActionResult GanhoPeso(int? pesoInicial, int? semana, int? pesoActual)
        {
            List<SelectListItem> lst = new List<SelectListItem>();
            for (int i = 1; i < 41; i++)
            {
                lst.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
            }
            ViewBag.Lst = lst;
            if (!pesoInicial.HasValue || !semana.HasValue || !pesoActual.HasValue)
                return View();

            double pWeight = (pesoInicial.Value * 1000.0) / 454.0;
            double cWeight = (pesoActual.Value * 1000.0) / 454.0;
            double lowWeight=0.0;
            double upWeight=0.0; 

            if (semana.Value < 8)
            {
                lowWeight = 0 + pWeight;
                upWeight = 0 + pWeight;
            }
            else if (semana.Value >= 8 && semana.Value <= 15)
            {
                lowWeight = Math.Round((-0.002604 * Math.Pow(semana.Value, 3)) + (0.1517857 * Math.Pow(semana.Value, 2)) - (1.81994 * Math.Pow(semana.Value, 1)) + 6.4178571 + pWeight);
                upWeight = Math.Round((0.0130208 * Math.Pow(semana.Value, 3)) - (0.379464 * Math.Pow(semana.Value, 2)) + (4.0550595 * Math.Pow(semana.Value, 1)) - 12.58214 + pWeight);
            }
            else if (semana.Value >= 16 && semana.Value <= 31)
            {
                lowWeight = Math.Round((0.000342 * Math.Pow(semana.Value, 3)) - (0.041126 * Math.Pow(semana.Value, 2)) + (2.3628096 * Math.Pow(semana.Value, 1)) - 23.16739 + pWeight);
                upWeight = Math.Round((-0.000789 * Math.Pow(semana.Value, 3)) + (0.0324675 * Math.Pow(semana.Value, 2)) + (1.1341089 * Math.Pow(semana.Value, 1)) - 14.778114 + pWeight);
            }
            else if (semana.Value >= 32)
            {
                lowWeight = Math.Round((0.0052083 * Math.Pow(semana.Value, 3)) - (0.616071 * (Math.Pow(semana.Value, 2))) + (24.33631 * Math.Pow(semana.Value, 1)) - 297.05 + pWeight);
                upWeight = Math.Round((-4.9 * Math.Pow(10, -16)) * Math.Pow(semana.Value, 3) - (0.040179 * Math.Pow(semana.Value, 2)) + (3.3303571 * Math.Pow(semana.Value, 1)) - 36.45 + pWeight);
            } 

            ViewBag.pesoIni =Math.Round((lowWeight*454)/1000);
            ViewBag.pesoFim =Math.Round((upWeight*454)/1000);
            ViewBag.semana = semana.Value;

            return View();
        }


        [HttpPost]
        public ActionResult FotoUpload(string qqfile)
        {
            string vPath = @"../Content/Images/FotosUser/";
            var path = Server.MapPath(@"~\Content\Images\FotosUser\");
            var file = string.Empty;
            var stream = Request.InputStream;
            string filename="";
            string fullFile = "";
            try
            {
                if (String.IsNullOrEmpty(Request["qqfile"]))
                {
                    // IE
                    HttpPostedFileBase postedFile = Request.Files[0];
                    stream = postedFile.InputStream;
                    
                    filename =System.IO.Path.GetFileName(Request.Files[0].FileName);
                    filename = filename.Insert(filename.LastIndexOf("."), DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                    file = Path.Combine(path, filename);
                    fullFile = vPath + filename;
                }
                else
                {
                    //Webkit, Mozilla
                    filename = qqfile.Insert(qqfile.LastIndexOf("."), DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                    file = Path.Combine(path, filename );
                    fullFile = vPath + filename;
                }

                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                System.IO.File.WriteAllBytes(file, buffer);

                ResizeImage(file, file, 120, 120, true);

                return Json(new { success = true, filename = filename, fullfile = fullFile }, "text/html");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message }, "application/json");
            }
            finally { stream.Close(); }
        }

        public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);


            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();

            // Save resized picture
            NewImage.Save(NewFile);
        }


    }

    class NomeDetailsJson
    {
        public string NomeProprio { get; set; }
        public string Descricao { get; set; }
        public string FacebookUrl { get; set; }
        public string Genero { get; set; }
    }
}
